#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

// 定义搜索函数
void search(const std::string& text, const std::string& query) {
    size_t count = 0;
    size_t pos = text.find(query);
    while (pos != std::string::npos) {
        count++;
        pos = text.find(query, pos + query.length());
    }
    std::cout << "The text contains '" << query << "' " << count << " times." << std::endl;
}

// 定义替换函数
void replace(std::string& text, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = text.find(from, start_pos)) != std::string::npos) {
        text.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
    std::cout << "Replaced text: " << text << std::endl;
}

// 定义提取数字函数
void extract(const std::string& text) {
    std::string numbers;
    std::copy_if(text.begin(), text.end(), std::back_inserter(numbers), ::isdigit);
    std::cout << "Extracted numbers: " << numbers << std::endl;
}

// main函数：解析命令行参数并调用相应的处理函数
//g++ -o text_tool main.cpp
//1 ./text_tool search "hello world, hello everyone" hello
//2 ./text_tool replace "hello world, hello everyone" hello hi
//3 ./text_tool extract "User1234Test567"
int main(int argc, char* argv[]) {
    if (argc < 3) {
        std::cerr << "Usage: " << argv[0] << " <command> <text> [args...]" << std::endl;
        return 1;
    }

    std::string command = argv[1];
    std::string text = argv[2];

    if (command == "search") {
        if (argc != 4) {
            std::cerr << "Usage: " << argv[0] << " search <text> <query>" << std::endl;
            return 1;
        }
        search(text, argv[3]);
    } else if (command == "replace") {
        if (argc != 5) {
            std::cerr << "Usage: " << argv[0] << " replace <text> <from> <to>" << std::endl;
            return 1;
        }
        replace(text, argv[3], argv[4]);
    } else if (command == "extract") {
        extract(text);
    } else {
        std::cerr << "Unknown command: " << command << std::endl;
        return 1;
    }

    return 0;
}